package com.zjy.spts.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by zjy629 on 2018/5/16.
 */
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter{
    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("filter init .....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("过滤器运行中");
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session= request.getSession();
       filterChain.doFilter(servletRequest,servletResponse);
       String name =  (String)session.getAttribute("name");
       String url = request.getRequestURL()+"";
       logger.info("url:"+url);
       if (name == null || "".equals(name)){
        //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
           if(url != null && !url.equals("")&& (url.indexOf("/user/login")<0) && url.indexOf("login")<0){
                response.sendRedirect(request.getContextPath()+"/login.html");
                return;
           }
       }
        filterChain.doFilter(servletRequest,servletResponse);
       return;
    }

    @Override
    public void destroy() {
        logger.info("filter destroy.....");
    }
}
